package util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DataUtil {
	public static Object saveData(String className,ResultSet rs)throws Exception{
		Object obj=null;
		try {
			Class cls = Class.forName(className);
			obj =  cls.newInstance();
			Method[] methods = cls.getDeclaredMethods();
			List<Method> lists = new ArrayList<Method>();
			for (int i=0;i<methods.length;i++) {
				if (methods[i].getName().startsWith("set")) {
					lists.add(methods[i]);
				}
			}
			Field[] fields =cls.getDeclaredFields();
			for (Method method : lists) {
				for (Field field : fields) {
					if (method.getName().equalsIgnoreCase("set"+field.getName())) {
						//System.out.println(Arrays.toString(method.getParameterTypes()));
						String type = Arrays.toString(method.getParameterTypes());
						if (type.equalsIgnoreCase("[int]")) {
							method.invoke(obj, rs.getInt(field.getName()));
							//System.out.println(rs.getInt(field.getName()));
						}else if (type.equalsIgnoreCase("[double]")) {
							method.invoke(obj, rs.getDouble(field.getName()));
							//System.out.println(rs.getDouble(field.getName()));
						}else if (type.equalsIgnoreCase("[boolean]")) {
							method.invoke(obj, rs.getInt(field.getName()));
						}
						else{
							String type1 = type.substring(type.lastIndexOf("."));
							//System.out.println(type1);
							if (type1.equalsIgnoreCase(".Integer]") || type1.equalsIgnoreCase(".Long]")) {
								//System.out.println(method.getName());
								method.invoke(obj, rs.getInt(field.getName()));
								//System.out.println(rs.getInt(field.getName()));
							}else if (type1.equalsIgnoreCase(".String]")) {
								method.invoke(obj, rs.getString(field.getName()));
								//System.out.println(rs.getString(field.getName()));
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("保存数据异常");
		}
		return obj;
	}
}
